package utils;

import okhttp3.*;

import java.io.IOException;

public class HttpUtils {
    /**
     * 定义post请求使用的json头
     */
    private static final MediaType JSON = MediaType.Companion.parse("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 不带token的post请求
     *
     * @param url  接口请求地址
     * @param json 接口请求的json字符串
     */
    public static Response post(String url, String json) throws IOException {
        RequestBody body = RequestBody.Companion.create(json, JSON);
        Request request = new Request.Builder().url(url).post(body).build();
        return client.newCall(request).execute();
    }

    /**
     * 带token的post请求
     *
     * @param token 字符串
     * @param url   接口请求地址
     * @param json  接口请求的json字符串
     */
    public static Response post(String token, String url, String json) throws IOException {
        RequestBody body = RequestBody.Companion.create(json, JSON);
        Request request = new Request.Builder().addHeader("Authorization", "JWT " + token).url(url).post(body).build();
        return client.newCall(request).execute();
    }

    /**
     * 带token的get请求
     *
     * @param token 字符串
     * @param url   接口请求地址
     */
    public static Response get(String token, String url) throws IOException {
        Request request = new Request.Builder().addHeader("Authorization", "JWT " + token).url(url).get().build();
        return client.newCall(request).execute();
    }

    /**
     * 带token的put请求
     *
     * @param token 字符串
     * @param url   接口请求地址
     * @param json  接口请求的json字符串
     */
    public static Response put(String token, String url, String json) throws IOException {
        RequestBody body = RequestBody.Companion.create(json, JSON);
        Request request = new Request.Builder().addHeader("Authorization", "JWT " + token).url(url).put(body).build();
        return client.newCall(request).execute();
    }

    /**
     * 带token的delete请求
     *
     * @param token 字符串
     * @param url   接口请求地址
     */
    public static Response delete(String token, String url) throws IOException {
        Request request = new Request.Builder().addHeader("Authorization", "JWT " + token).url(url).delete().build();
        return client.newCall(request).execute();
    }
}
